<template>
  <el-dialog
    v-model="visible"
    title="SQL预览与执行"
    width="80%"
    :close-on-click-modal="false"
    @close="handleClose"
    class="sql-preview-dialog"
  >
    <div class="sql-preview-content">
      <!-- SQL编辑器 -->
      <div class="sql-editor-section">
        <div class="section-header">
          <h4>SQL语句</h4>
          <div class="editor-actions">
            <el-button size="small" @click="formatSQL">
              <el-icon><MagicStick /></el-icon>
              格式化
            </el-button>
            <el-button size="small" @click="copySQL">
              <el-icon><CopyDocument /></el-icon>
              复制
            </el-button>
            <el-button size="small" @click="downloadSQL">
              <el-icon><Download /></el-icon>
              下载
            </el-button>
          </div>
        </div>
        
        <div class="sql-editor">
          <el-input
            v-model="sqlContent"
            type="textarea"
            :rows="12"
            placeholder="SQL语句将在这里显示..."
            class="sql-textarea"
          />
        </div>
      </div>

      <!-- 执行结果 -->
      <div class="execution-section" v-if="executionResult">
        <div class="section-header">
          <h4>执行结果</h4>
          <el-tag
            :type="executionResult.success ? 'success' : 'danger'"
            size="small"
          >
            {{ executionResult.success ? '成功' : '失败' }}
          </el-tag>
        </div>
        
        <div class="execution-content">
          <div v-if="executionResult.success" class="success-result">
            <el-alert
              :title="executionResult.message"
              type="success"
              :closable="false"
              show-icon
            />
            
            <!-- 查询结果表格 -->
            <div v-if="executionResult.data && executionResult.data.length > 0" class="result-table">
              <el-table
                :data="executionResult.data"
                border
                size="small"
                max-height="300"
                style="margin-top: 16px;"
              >
                <el-table-column
                  v-for="column in resultColumns"
                  :key="column"
                  :prop="column"
                  :label="column"
                  min-width="120"
                />
              </el-table>
            </div>
            
            <!-- 执行统计 -->
            <div class="execution-stats" v-if="executionResult.stats">
              <el-descriptions :column="3" size="small" border>
                <el-descriptions-item label="执行时间">
                  {{ executionResult.stats.executionTime }}ms
                </el-descriptions-item>
                <el-descriptions-item label="影响行数">
                  {{ executionResult.stats.affectedRows }}
                </el-descriptions-item>
                <el-descriptions-item label="返回行数">
                  {{ executionResult.stats.returnedRows }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
          
          <div v-else class="error-result">
            <el-alert
              :title="executionResult.message"
              type="error"
              :closable="false"
              show-icon
            />
            
            <!-- 错误详情 -->
            <div v-if="executionResult.error" class="error-details">
              <el-collapse>
                <el-collapse-item title="错误详情" name="error">
                  <pre class="error-text">{{ executionResult.error }}</pre>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
        </div>
      </div>

      <!-- SQL语法检查 -->
      <div class="syntax-check-section">
        <div class="section-header">
          <h4>语法检查</h4>
          <el-button size="small" @click="checkSyntax" :loading="syntaxChecking">
            <el-icon><CircleCheck /></el-icon>
            检查语法
          </el-button>
        </div>
        
        <div class="syntax-result" v-if="syntaxResult">
          <el-alert
            :title="syntaxResult.message"
            :type="syntaxResult.valid ? 'success' : 'warning'"
            :closable="false"
            show-icon
          />
          
          <div v-if="syntaxResult.warnings && syntaxResult.warnings.length > 0" class="syntax-warnings">
            <h5>语法建议：</h5>
            <ul>
              <li v-for="warning in syntaxResult.warnings" :key="warning">
                {{ warning }}
              </li>
            </ul>
          </div>
        </div>
      </div>

      <!-- 执行选项 -->
      <div class="execution-options">
        <el-card shadow="never" class="options-card">
          <template #header>
            <span>执行选项</span>
          </template>
          
          <el-form :model="executionConfig" label-width="120px" size="small">
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="执行模式">
                  <el-select v-model="executionConfig.mode" style="width: 100%">
                    <el-option label="实际执行" value="execute" />
                    <el-option label="仅验证" value="validate" />
                    <el-option label="解释计划" value="explain" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="超时时间">
                  <el-input-number
                    v-model="executionConfig.timeout"
                    :min="1"
                    :max="300"
                    style="width: 100%"
                    placeholder="秒"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="最大返回行数">
                  <el-input-number
                    v-model="executionConfig.maxRows"
                    :min="1"
                    :max="10000"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row>
              <el-col :span="24">
                <el-form-item>
                  <el-checkbox v-model="executionConfig.autoCommit">自动提交</el-checkbox>
                  <el-checkbox v-model="executionConfig.showPlan">显示执行计划</el-checkbox>
                  <el-checkbox v-model="executionConfig.logExecution">记录执行日志</el-checkbox>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button
          type="primary"
          @click="executeSQL"
          :loading="executing"
          :disabled="!sqlContent.trim()"
        >
          <el-icon><CaretRight /></el-icon>
          执行SQL
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  MagicStick,
  CopyDocument,
  Download,
  CircleCheck,
  CaretRight
} from '@element-plus/icons-vue'

export default {
  name: 'SQLPreview',
  components: {
    MagicStick,
    CopyDocument,
    Download,
    CircleCheck,
    CaretRight
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    sql: {
      type: String,
      default: ''
    },
    databaseType: {
      type: String,
      default: 'mysql'
    }
  },
  emits: ['update:modelValue', 'execute'],
  setup(props, { emit }) {
    const executing = ref(false)
    const syntaxChecking = ref(false)
    const sqlContent = ref('')
    const executionResult = ref(null)
    const syntaxResult = ref(null)

    // 执行配置
    const executionConfig = reactive({
      mode: 'execute',
      timeout: 30,
      maxRows: 1000,
      autoCommit: true,
      showPlan: false,
      logExecution: true
    })

    // 计算属性
    const visible = computed({
      get: () => props.modelValue,
      set: (value) => emit('update:modelValue', value)
    })

    const resultColumns = computed(() => {
      if (!executionResult.value?.data || executionResult.value.data.length === 0) {
        return []
      }
      return Object.keys(executionResult.value.data[0])
    })

    // 监听SQL变化
    watch(() => props.sql, (newSQL) => {
      sqlContent.value = newSQL
      executionResult.value = null
      syntaxResult.value = null
    }, { immediate: true })

    // 格式化SQL
    const formatSQL = () => {
      if (!sqlContent.value.trim()) {
        ElMessage.warning('请先输入SQL语句')
        return
      }

      // 简单的SQL格式化
      let formatted = sqlContent.value
        .replace(/\s+/g, ' ')
        .replace(/,\s*/g, ',\n  ')
        .replace(/\(\s*/g, '(\n  ')
        .replace(/\s*\)/g, '\n)')
        .replace(/\bSELECT\b/gi, 'SELECT')
        .replace(/\bFROM\b/gi, '\nFROM')
        .replace(/\bWHERE\b/gi, '\nWHERE')
        .replace(/\bINNER JOIN\b/gi, '\nINNER JOIN')
        .replace(/\bLEFT JOIN\b/gi, '\nLEFT JOIN')
        .replace(/\bRIGHT JOIN\b/gi, '\nRIGHT JOIN')
        .replace(/\bORDER BY\b/gi, '\nORDER BY')
        .replace(/\bGROUP BY\b/gi, '\nGROUP BY')
        .replace(/\bHAVING\b/gi, '\nHAVING')
        .replace(/\bCREATE TABLE\b/gi, 'CREATE TABLE')
        .replace(/\bINSERT INTO\b/gi, 'INSERT INTO')
        .replace(/\bUPDATE\b/gi, 'UPDATE')
        .replace(/\bDELETE FROM\b/gi, 'DELETE FROM')

      sqlContent.value = formatted.trim()
      ElMessage.success('SQL格式化完成')
    }

    // 复制SQL
    const copySQL = async () => {
      if (!sqlContent.value.trim()) {
        ElMessage.warning('没有可复制的SQL语句')
        return
      }

      try {
        await navigator.clipboard.writeText(sqlContent.value)
        ElMessage.success('SQL已复制到剪贴板')
      } catch (error) {
        ElMessage.error('复制失败')
      }
    }

    // 下载SQL
    const downloadSQL = () => {
      if (!sqlContent.value.trim()) {
        ElMessage.warning('没有可下载的SQL语句')
        return
      }

      const blob = new Blob([sqlContent.value], { type: 'text/sql' })
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `sql_${Date.now()}.sql`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
      
      ElMessage.success('SQL文件下载成功')
    }

    // 检查语法
    const checkSyntax = async () => {
      if (!sqlContent.value.trim()) {
        ElMessage.warning('请先输入SQL语句')
        return
      }

      syntaxChecking.value = true
      
      try {
        // 模拟语法检查
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 简单的语法检查逻辑
        const sql = sqlContent.value.toUpperCase()
        const warnings = []
        
        if (!sql.includes('CREATE') && !sql.includes('SELECT') && 
            !sql.includes('INSERT') && !sql.includes('UPDATE') && 
            !sql.includes('DELETE')) {
          warnings.push('未识别的SQL语句类型')
        }
        
        if (sql.includes('SELECT *')) {
          warnings.push('建议避免使用 SELECT *，明确指定需要的字段')
        }
        
        if (sql.includes('WHERE') && !sql.includes('LIMIT') && sql.includes('SELECT')) {
          warnings.push('建议在查询语句中使用 LIMIT 限制返回行数')
        }

        syntaxResult.value = {
          valid: true,
          message: '语法检查通过',
          warnings: warnings
        }
        
        ElMessage.success('语法检查完成')
      } catch (error) {
        syntaxResult.value = {
          valid: false,
          message: '语法检查失败',
          warnings: []
        }
        ElMessage.error('语法检查失败')
      } finally {
        syntaxChecking.value = false
      }
    }

    // 执行SQL
    const executeSQL = async () => {
      if (!sqlContent.value.trim()) {
        ElMessage.warning('请先输入SQL语句')
        return
      }

      executing.value = true
      executionResult.value = null

      try {
        // 模拟SQL执行
        await new Promise(resolve => setTimeout(resolve, 2000))
        
        const sql = sqlContent.value.toUpperCase()
        
        if (sql.includes('CREATE TABLE')) {
          // 创建表成功
          executionResult.value = {
            success: true,
            message: '表创建成功',
            stats: {
              executionTime: Math.floor(Math.random() * 1000) + 100,
              affectedRows: 0,
              returnedRows: 0
            }
          }
        } else if (sql.includes('SELECT')) {
          // 查询结果
          executionResult.value = {
            success: true,
            message: '查询执行成功',
            data: [
              { id: 1, name: '示例数据1', status: '活跃' },
              { id: 2, name: '示例数据2', status: '非活跃' },
              { id: 3, name: '示例数据3', status: '活跃' }
            ],
            stats: {
              executionTime: Math.floor(Math.random() * 500) + 50,
              affectedRows: 0,
              returnedRows: 3
            }
          }
        } else {
          // 其他操作
          executionResult.value = {
            success: true,
            message: 'SQL执行成功',
            stats: {
              executionTime: Math.floor(Math.random() * 800) + 200,
              affectedRows: Math.floor(Math.random() * 10) + 1,
              returnedRows: 0
            }
          }
        }
        
        emit('execute', sqlContent.value)
        ElMessage.success('SQL执行成功')
      } catch (error) {
        executionResult.value = {
          success: false,
          message: 'SQL执行失败',
          error: 'Table \'test_table\' doesn\'t exist\n\nSQL State: 42S02\nError Code: 1146'
        }
        ElMessage.error('SQL执行失败')
      } finally {
        executing.value = false
      }
    }

    // 关闭对话框
    const handleClose = () => {
      visible.value = false
      executionResult.value = null
      syntaxResult.value = null
    }

    return {
      visible,
      executing,
      syntaxChecking,
      sqlContent,
      executionResult,
      syntaxResult,
      executionConfig,
      resultColumns,
      formatSQL,
      copySQL,
      downloadSQL,
      checkSyntax,
      executeSQL,
      handleClose
    }
  }
}
</script>

<style scoped>
.sql-preview-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.sql-preview-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.editor-actions {
  display: flex;
  gap: 8px;
}

.sql-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.sql-textarea {
  :deep(.el-textarea__inner) {
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    font-size: 14px;
    line-height: 1.5;
    border: none;
    resize: vertical;
  }
}

.execution-content {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  padding: 16px;
}

.success-result {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.error-result {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.error-text {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 12px;
  color: #e74c3c;
  margin: 0;
  white-space: pre-wrap;
}

.syntax-warnings {
  margin-top: 12px;
  padding: 12px;
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 4px;
}

.syntax-warnings h5 {
  margin: 0 0 8px 0;
  color: #856404;
}

.syntax-warnings ul {
  margin: 0;
  padding-left: 20px;
  color: #856404;
}

.options-card {
  :deep(.el-card__header) {
    padding: 12px 16px;
    background: #fafafa;
  }
  
  :deep(.el-card__body) {
    padding: 16px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
  background: #fafafa;
}

:deep(.el-descriptions) {
  margin-top: 16px;
}

:deep(.el-collapse-item__header) {
  font-size: 14px;
}
</style>